<?php

/**
 * @Author: king
 * @Date:   2019-05-05 19:58:37
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-03 23:23:30
 */

namespace App\Http\Controllers\Api\v1\Order;

use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\v1\Order\CheckOrderController;
use App\Tools\Orders as OrdersLib;
use App\Models\Api\Orders as OrdersModel;
use App\Models\Api\Recode;
use App\Models\Api\LanmeiCounselorProblemRecode;
use App\Models\Api\LanmeiOrderRefund;
use App\Models\Api\LanmeiCourse;
use Illuminate\Http\Request;
use App\Exceptions\ApiException;
use DB;


/**
 * 教学视频订单相关接口
 * Class Orders
 * @package app\api\controller\v9
 */
class IndexController extends BaseController
{
    protected $nodel;
    public function __construct()
    {
        parent::__construct();
        $this->nodel = config('code.nodel');
    }

    /**
     * 订单列表相关接口
     * @return \response\Json
     */
    public function index(Request $request)
    {
        if (!$request->isMethod('get'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $type = $request->input('type', 0);

        $page = $request->input('page', 1);

        $uid = $request->uid;

        //判断订单是否超时未支付
        check_overtime($uid);

        $OrdersModel = new OrdersModel();

        $orders = $OrdersModel->getUidOrders(['uid' => $uid, 'type' => $type, 'is_del' => $this->nodel, 'page' => $page]);
        $RecodeModel = new Recode();
        $LanmeiRecodeModel = new LanmeiCounselorProblemRecode();

        //重组订单数据
        $start_time = '';
        $end_time = '';

        $data = [];

        if ($orders['data'] || !empty($orders['data']))
        {
            foreach ($orders['data'] as $k => $v)
            {
                if (isset($v['type']) && $v['type'])
                {
                    switch ($v['type'])
                    {
                        case 1:
                            $start_time = date('Y-m-d', $v['time']);
                            $end_time = date('Y-m-d', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                        case 2:
                            $start_time = date('Y-m', $v['time']);
                            $end_time = date('Y-m', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                        case 3:
                            $start_time = date('Y', $v['time']);
                            $end_time = date('Y', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                    }
                }

                if (isset($v['or_prize'], $v['now_prize']))
                {
                    $or_price = sprintf("%.2f", $v['or_prize']);
                    $now_price = sprintf("%.2f", $v['now_prize']);
                } else
                {
                    $or_price = sprintf("%.2f", $v['counselor_price']);
                    $now_price = sprintf("%.2f", $v['counselor_price']);
                }

                $total_amount = sprintf("%.2f", $v['total_amount']);
                $create_time = date('Y-m-d H:i:s', strtotime($v['create_time']));

                //生时校正订单数据
                if ($v['order_type'] == 1 && $this->headers['version']>='1.0.0')
                {
                    if ($v['status'] == 2)
                    {
                        $v['status'] = 5;//交易关闭
                    } elseif ($v['status'] == 3)
                    {
                        $v['status'] = 6;//退款成功
                    } elseif ($v['status'] == 4)
                    {
                        $v['status'] = 2;//矫正成功
                    } elseif ($v['status'] == 5)
                    {
                        $v['status'] = 3;//矫正失败
                    }
                    $data[] = [
                        'type' => 1,
                        'rectification_data' => [
                            'id' => $v['reid'],
                            'birth' => date('Y-m-d', $v['start_time']),
                            'start_time' => date('H:i', $v['start_time']),
                            'end_time' => date('H:i', $v['end_time']),
                            'or_prize' => $or_price,
                            'now_prize' => $now_price,
                        ],
                        'status' => $v['status'],
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                        'total_price' => $total_amount,
                    ];
                }//运势订单数据(运势)
                elseif (($this->headers['version']>='1.0.0' && $v['order_type'] == 2) || ($this->headers['version']>='1.0.0' && in_array($v['order_type'],[3,4])))
                {
                    $a[] = $v;
                    $array = [];
                    $rids_array = explode(',', $v['rids']);
                    foreach ($rids_array as $kk => $vv)
                    {
                        if ($vv)
                        {
                            try
                            {

                                $rname = $RecodeModel->getRecode(['id' => $vv]);

                            }
                            catch (\Exception $e)
                            {

                                $rname = [
                                    'id' => $vv,
                                    'name' => '未找到',
                                ];
                                \Log::info('异常档案id：' . $vv);
                            }
                        } else
                        {
                            $rname = [
                                'id' => $vv,
                                'name' => '未找到',
                            ];
                        }

                        $array[] = [
                            'id' => $rname['id'],
                            'gid' => $v['gid'],
                            'rname' => $rname['name'],
                            'fortune_type' => $v['type'],
                            'start_time' => $start_time,
                            'end_time' => $end_time,
                            'or_price' => $or_price,
                            'now_price' => $now_price,
                        ];
                    }
                    $data[] = [
                        'type' => 2,
                        'fortune_data' => $array,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => count($array),
                        'total_price' => $total_amount,
                    ];

                }//命格线订单数据
                elseif ($v['order_type'] == 5 && $this->headers['version']>='1.0.0')
                {
                    $gname = [];

                    try
                    {

                        $rname = $RecodeModel->getRecode(['id' => $v['rid']]);

                    }
                    catch (\Exception $e)
                    {

                        $rname = [
                            'name' => '未找到',
                        ];
                        \Log::info('异常档案id：' . $v['rid']);
                    }

                    try
                    {
                        $ogoods = DB::table('orders_goods')
                            ->from('orders_goods as og')
                            ->join('goods as g', 'og.gid','=','g.id', 'LEFT')
                            ->select('g.name')
                            ->where(['og.oid' => $v['oid']])
                            ->get();

                    }
                    catch (\Exception $e)
                    {

                        \Log::info('异常订单id：' . $v['oid']);

                        return show(config('code.error'), '订单异常');
                    }

                    foreach ($ogoods as $i => $g)
                    {
                        $gname[] = $g['name'];
                    }

                    $data[] = [
                        'type' => 3,
                        'acgmap_data' => [
                            'order_name' => '占星地图',
                            'order_sub_name' => '占星地图解锁',
                            'order_sub_rname' => $rname['name'],
                            'order_sub_names' => implode(',', $gname),
                        ],
                        'total_price' => $total_amount,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => count($ogoods),
                    ];

                } elseif ($v['order_type'] == 6 && $this->headers['version']>='1.0.0')
                {
                    //获取相关课程信息
                    $LanmeiCourseModel = new LanmeiCourse();

                    $course = $LanmeiCourseModel->getCourseInfo(['gid' => $v['gid']]);

                    if ($course === false)
                    {
                        return show(config('code.error'), $LanmeiCourseModel->getError());
                    }

                    $data[] = [
                        'type' => 4,
                        'video_data' => [
                            'id' => $course['id'],
                            'order_name' => '课程',
                            'order_sub_name' => '占星课程',
                            'course_title' => $course['title'],
                            'or_price' => $or_price,
                            'now_price' => $now_price,
                        ],
                        'total_price' => $total_amount,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                    ];
                } elseif (in_array($v['order_type'], [7, 8, 9]) && $this->headers['version']>='2.0.0')
                {
                    $answer = '';
                    $rname = [];
                    $divination = '';
                    switch ($v['order_type'])
                    {
                        case 7:
                            $name = '占卜咨询';
                            $type = 6;
                            $divination = [
                                'planet' => config('astro.planet_name')[$v['planet']],
                                'sign' => config('astro.sign_name')[$v['sign']],
                                'house' => $v['house'] . '宫'
                            ];
                            $divination = implode(' ', $divination);
                            break;
                        case 8:
                            $name = '占星咨询';
                            $type = 5;
                            $recode = array_values($LanmeiRecodeModel->getProblemRecodeName($v['bind_id']));
                            foreach ($recode as $r)
                            {
                                $rname[] = $r['name'];
                            }
                            break;
                        case 9:
                            $name = '围观';
                            $type = 7;
                            $answer = '';
                            break;
                        default:
                            $name = '';
                    }
                    $data[] = [
                        'type' => $type,
                        'counselor_data' => [
                            'order_name' => $name,
                            'title' => $v['title'],
                            'anwer' => $answer,
                            'recode' => $rname,
                            'divination' => $divination,
                            'or_price' => $or_price,
                            'now_price' => $now_price,
                        ],
                        'total_price' => $total_amount,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                    ];
                }
            }
        }
        $orders['data'] = $data;

        return show(config('code.success'), '加载成功', $orders);
    }

  /**
     * @title
     * @method PUT
     * @desc
     * @return array
     */
    public function del(Request $request)
    {
        if (!$request->isMethod('delete'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $order_id = $request->input('order_id');
        if (!$order_id)
        {
            return show(config('code.error'), 'order_id不存在', '', 400);
        }
        $OrdersModel = new OrdersModel();
//        判断当前订单是否存在
        $where = ['order_id' => $order_id,['status','!=', -1]];
        $n_data = $OrdersModel->where($where)->first();
        if (empty($n_data))
        {
            return show(config('code.error'), 'order is not exist.', [], 403);
        }
        // 进行软删除
//        $rectification->delete();
        try
        {
            $OrdersModel->where('order_id', $order_id)->update(['is_del' => config('code.del')]);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }

        // 删除订单缓存
       $OrdersModel->rm_cache(['uid' => $request->uid,  'type' => 3, 'order_id' => $order_id]);

        return show(config('code.success'), '删除成功', []);

    }

    /**
     * 订单详情相关接口
     * @param['type']  [1=>生时矫正,2=>运势,3=>命运之城,4=>教学视频，5=>占星，6=>占卜,7=>围观]
     * @return \response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \db\exception\DataNotFoundException
     * @throws \db\exception\ModelNotFoundException
     * @throws \exception\DbException
     */
    public function read(Request $request)
    {
        if (!$request->isMethod('get'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = $request->only(['order_id']);

        $uid = $request->uid;

        $validate = new \App\Tools\Validates\Orders();

        //验证请求参数
        if ($validate->scene('read')->check($param) !== true)
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        //支付客户端判断该订单是否已经支付,若已经支付,但是status=0;就更改status=1
        $validateResult = (new OrdersLib())->validate_orders(['order_id' => $param['order_id'], 'is_pay_again' => false, 'uid' => $uid]);

        if ($validateResult !== true)
        {
            return show(config('code.error'), $validateResult);
        }

        $OrdersModel = new OrdersModel();
        $LanmeiRecodeModel = new LanmeiCounselorProblemRecode();
        $order_ids[] = $param['order_id'];
        $order_type = (int)substr($param['order_id'], 1, 1);
        //获取订单数据
        if ($order_type == 3)
        {
            $field = ['og.gid','g.name','g.or_prize','g.now_prize','g.expire_time','or.id as oid','or.status','or.order_id','or.uid','or.trade_type','or.total_amount','or.create_time','or.pay_time','or.return_time','og.rid','or.account'];
            $orders = $OrdersModel->from('orders as or')
                ->select($field)
                ->join('orders_goods as og', 'or.id','=','og.oid', 'INNER')
                ->join('goods as g', 'og.gid','=','g.id', 'INNER')
                ->where('or.order_id', $param['order_id'])
                ->orderBy('or.create_time', 'DESC')
                ->get();
            $orders = json_decode(json_encode($orders,true),true);
        } else
        {
            //获取订单数据
            $orders = $OrdersModel->get_orders_detail(['order_type' => $order_type, 'order_ids' => $order_ids, 'uid' => $uid]);
        }

        if (is_array($orders) && $orders)
        {
            $num = 1;
            $arr = [];
            $or_total = 0;
            $now_total = 0;
            $rname = [];
            //重组订单数据
            foreach ($orders as $data)
            {
                $oid = $data['oid'];
                $arr['status'] = $data['status'];
                $create_time = date('Y-m-d H:i:s',  strtotime($data['create_time']));
                $return_time = $data['return_time'] ? date('Y-m-d H:i:s', $data['return_time']) : 0;
                //获取订单商品原价与现价
                if (isset($data['or_prize']) && isset($data['now_prize']))
                {
                    //  判断是否是applePay
                    if ($this->is_apple_pay)
                    {
                        switch ($order_type)
                        {
                            case 1:
                                $data['or_price'] = $this->apple_goods['rec_goods']['or_prize'];
                                $data['now_price'] = $this->apple_goods['rec_goods']['now_prize'];
                                break;
                            case 2:
                                foreach ($this->apple_goods['fortune_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                            case 3:
                                foreach ($this->apple_goods['acg_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                            case 4;
                                foreach ($this->apple_goods['video_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                        }
                    } else
                    {
                        $data['or_price'] = sprintf("%.2f", $data['or_prize']);
                        $data['now_price'] = sprintf("%.2f", $data['now_prize']);
                        //商品活动折扣
                        $activeDiscount = active($data['gid']);
                        if ($activeDiscount['discount'])
                        {
                            $data['now_price'] *= $activeDiscount['discount'];
                        }
                    }

                } else
                {
                    $data['or_price'] = sprintf("%.2f", $data['counselor_price']);
                    $data['now_price'] = sprintf("%.2f", $data['counselor_price']);
                }

                //获取不同类型订单的详情数据
                switch (true)
                {
                    //运势
                    case $order_type == 2:
                        $arr['fortune'] = $this->FortuneRead($data);
                        $num = count($arr['fortune']);
                        $or_total = $data['or_price'] * $num;
                        $now_total = $data['now_price'] * $num;
                        break;
                    //占星地图
                    case $order_type == 3:
                        $arr['lines'][] = $this->MapRead($data);
                        $num = count($arr['lines']);
                        $or_total += $data['or_price'];
                        $now_total += $data['now_price'];
                        break;
                    //占星视频
                    case $order_type == 4:
                        $arr['video'] = $this->VideoRead($data);
                        $or_total = $data['or_price'];
                        $now_total = $data['now_price'];
                        break;
                    //平台
                    case $order_type == 5:
                        $divination = [
                            'planet' => config('astro.planet_name')[$data['planet']],
                            'sign' => config('astro.sign_name')[$data['sign']],
                            'house' => $data['house'] . '宫'
                        ];
                        $data['divination'] = implode(' ', $divination);
                        $data['name'] = '占卜咨询';
                        $arr['questions_data'] = $this->PlatformRead($data, 1);
                        $or_total = $data['or_price'];
                        $now_total = $data['now_price'];
                        break;
                    case $order_type == 6:
                        $recode = array_values($LanmeiRecodeModel->getProblemRecodeName($data['bind_id']));
                        foreach ($recode as $r)
                        {
                            $data['recode'][] = $r['name'];
                        }
                        $data['name'] = '占星咨询';
                        $arr['questions_data'] = $this->PlatformRead($data, 2);
                        $or_total = $data['or_price'];
                        $now_total = $data['now_price'];
                        break;
                    case $order_type == 7:
                        $data['name'] = '围观';
                        $arr['questions_data'] = $this->PlatformRead($data, 3);
                        $or_total = $data['or_price'];
                        $now_total = $data['now_price'];
                        break;
                }

                //获取订单购买份数
                $arr['count'] = $num;
                //获取订单不同状态时的相关时间
                switch (true)
                {
                    case in_array($data['status'], [1, 4, 5]):
                        $arr['desc'] = '您购买的相关内容已成功解锁';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ],
                            1 => [
                                'name' => '支付时间',
                                'value' => date('Y-m-d H:i:s', $data['pay_time'])
                            ],
                        ];
                        break;
                    case 2:
                        $arr['desc'] = '24小时之内未付款订单自动关闭~';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ]
                        ];
                        break;
                    default:
                        $arr['desc'] = '您的订单还没有支付~';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ]
                        ];
                        break;
                }

                $arr['or_total_price'] = sprintf("%.2f", $or_total);
                $arr['total_price'] = sprintf("%.2f", $now_total);
                $arr['trade_type'] = $data['trade_type'];
                $arr['order_id'] = $param['order_id'];
                $arr['order_type'] = $order_type;
            }

            //获取订单退款信息
            $OrderRefundModel = new LanmeiOrderRefund();

            $RefundInfo = $OrderRefundModel->getOrderRefund($oid);
            //平台咨询订单返回退款的具体信息
            if (in_array($order_type, [5, 6]))
            {
                $arr['refund_info'] = [];
                if ($RefundInfo)
                {
                    foreach ($RefundInfo as $re)
                    {
                        $arr['refund_info'][] = [
                            'name' => $re['name'],
                            'price' => $re['price'],
                            'time' => date('Y-m-d H:i:s', $re['return_time'])
                        ];
                    }
                }
            } else
            {
                if ($return_time)
                {
                    $arr['desc'] = '您申请的退款已成功退回到您的账户~';
                    $arr['order'][] = [
                        'name' => '退款时间',
                        'value' => $return_time
                    ];
                }
            }

            return show(config('code.success'), '加载成功', $arr);
        } else
        {
            return show(config('code.error'), '当前订单不存在');

        }
    }

    /**
     * 运势订单详情
     * @param array $data
     * @return array|\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function FortuneRead($data = [])
    {
        switch ($data['type'])
        {
            case 1:
                $start_time = date('Y-m-d', $data['time']);
                $end_time = date('Y-m-d', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            case 2:
                $start_time = date('Y-m', $data['time']);
                $end_time = date('Y-m', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            case 3:
                $start_time = date('Y', $data['time']);
                $end_time = date('Y', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            default :
                return show(config('code.error'), '订单详情获取失败');
        }

        $RecodeModel = new Recode();
        $rids = explode(',', $data['rids']);
        $arr = [];
        if ($rids)
        {
            foreach ($rids as $k => $v)
            {
                $rname = $RecodeModel->getRecode(['id' => $v]);
                $arr[] = [
                    'id' => $rname['id'],
                    'gid' => $data['gid'],
                    'rname' => $rname['name'],
                    'fortune_type' => $data['type'],
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'or_price' => sprintf('%.2f', $data['or_price']),
                    'now_price' => sprintf('%.2f', $data['now_price']),
                ];
            }
        }

        return $arr;
    }

    /**
     * 占星地图订单详情
     * @param array $data
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    public function MapRead($data = [])
    {
        //重组订单详情数据
        $RecodeModel = new Recode();
        //获取当前订单的档案信息
        $recode = $RecodeModel->getRecode(['id' => $data['rid']]);

        if ($recode['isself'] == 1)
        {
            $rname = '自己';
        } else
        {
            $rname = $recode['name'];
        }

        $array = [
            'rid' => $data['rid'],
            'rname' => $rname,
            'name' => $data['name'],
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf("%.2f", $data['now_price']),
        ];

        return $array;
    }

    /**
     * 教学视频订单详情
     * @param array $data
     * @return array
     */
    public function VideoRead($data = [])
    {
        $arr = [
            'id' => $data['cid'],
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf('%.2f', $data['now_price']),
            'course_name' => '占星课程',
            'course_title' => $data['title'],
        ];
        return $arr;
    }

    /**
     * 平台订单详情
     * @param array $data
     * @return array
     */
    public function PlatformRead($data = [], $type = 0)
    {
        $arr = [
            'type' => $type,
            'order_name' => $data['name'],
            'title' => $data['title'],
            'answer' => $data['answer'] ?? '',
            'recode' => $data['recode'] ?? [],
            'divination' => $data['divination'] ?? '',
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf('%.2f', $data['now_price']),
            'cp_id' => $data['gid'],
        ];

        return $arr;
    }

    /**
     * 教学视频下单接口
     * @return \response\Json
     */
    public function pay_unlock(Request $request)
    {
        if (!$request->isMethod('post'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = $request->all();

        $validate = new \App\Tools\Validates\Orders();

       if ($validate->scene('v5_pay_unlock')->check($param) !== true)
        {
            return show(config('code.error'), json_encode($validate->getError(), true));
        }

        // 支付方式 3 为余额支付
        $trade_type = $param['trade_type'];
        // 商品类型id   1=>生时校正
        $gid = $param['gid'];
        // 选择的档案id，字符串
        $rids = $param['rids'];
        // 选择的解锁日期,字符串类型
        $start_time = $param['time'];
        //运势类型id
        $fortune_type = $param['fortune_type'];
        // openid
        $openid = $request->input('openid', '');
        // pay-redirect-url
        $callback_url = $request->input('callback_url', '');

         switch (true) {
            case in_array($gid, config('app.day_id')):
                $order_type = 2;
                break;
            case in_array($gid, config('app.month_id')):
                $order_type = 3;
                break;
            case in_array($gid, config('app.year_id')):
                $order_type = 4;
                break;
            default :
                return show(config('code.error'), '未知商品');
        }

        $OrderPayModel = new OrdersPayController();
        $data = $OrderPayModel->pay_unlock(['order_type' => $order_type, 'trade_type' => $trade_type, 'gid' => $gid, 'fortune_type' => $fortune_type, 'rids' => $rids, 'start_time' => $start_time, 'openid' => $openid, 'callback_url' => $callback_url]);

        if ($data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);
        } else
        {
            return show(config('code.error'), '下单失败', $data['data']);
        }
    }
    /**
     * 订单重新支付
     * @return \response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \db\exception\DataNotFoundException
     * @throws \db\exception\ModelNotFoundException
     * @throws \exception\DbException
     * @throws \Exception
     */
    public function pay_again(Request $request)
    {
        if (!$request->isMethod('POST'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = $request->all();

        $validate = new \App\Tools\Validates\Orders();

        if ($validate->scene('pay_again')->check($param) !== true)
        {
            return show(config('code.error'), json_encode($validate->getError(), true));
        }

        $trade_type = $param['trade_type'];// 支付方式

        $order_id = $param['order_id'];// 订单编号

        $openid = $request->input('openid', '');// openid

        $callback_url = $param['callback_url'] ?? '';

        $OrdersLib = new OrdersLib();

        //支付客户端判断该订单是否已经支付,若已经支付,但是status=0;就更改status=1
        $validateResult = $OrdersLib->validate_orders(['order_id' => $order_id, 'is_pay_again' => true,'uid'=>$request->uid]);

        if($validateResult !== true)
        {
            return show(config('code.error'),$validateResult);
        }

        $num = substr($order_id, 1, 1);

        $OrdersModel = new OrdersModel();
        $CheckOrders = new CheckOrderController();
        $RecodeModel = new Recode();
        //检测当前订单是否存在
        try
        {
            $where = ['o.order_id' => $order_id, 'o.is_del' => 0];
            $order = $OrdersModel
                ->from('orders as o')
                ->select('o.id','o.order_id','o.gid','o.status','o.trade_type','o.reid','o.fid','o.total_amount','o.uid','og.rid as orid','re.rid as rrid','f.rids')
                ->join('orders_goods as og', 'o.id','=','og.oid', 'LEFT')
                ->join('fortune as f', 'o.fid','=','f.id', 'LEFT')
                ->join('rectification as re', 'o.reid','=','re.id', 'LEFT')
                ->where($where)
                ->first();
        $order =json_decode(json_encode($order, true), true);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '当前订单不存在');
        }
        if (!$order)
        {
            throw new ApiException('当前订单不存在', 200, config('code.error'));
        }

        //判断购买的档案的订单是否被删除
        switch ($num)
        {
            case 1:
                $rid = $order['rrid'];
                $recode = $RecodeModel->getRecode(['id' => $rid]);
                if ($recode['status'] == 0 || !$recode['status'])
                {
                    return show(config('code.error'), '该订单的档案已删除，无法支付');
                }
                break;
            case 2:
                $rids = explode(',', $order['rids']);
                foreach ($rids as $rid)
                {
                    $recode = $RecodeModel->getRecode(['id' => $rid]);
                    if ($recode['status'] == 0 || !$recode['status'])
                    {
                        return show(config('code.error'), '该订单有档案已删除，无法支付');
                    }
                }
                break;
            case 3:
                $rid = $order['orid'];
                $recode = $RecodeModel->getRecode(['id' => $rid]);
                if ($recode['status'] == 0 || !$recode['status'])
                {
                    return show(config('code.error'), '该订单的档案已删除，无法支付');
                }
                break;
        }

        // 检查商品是否已经购买
        $CheckOrders->check_old_orders($order_id);
        switch ($num)
        {
            case 1:
                $pay_des = '准吖 - 生时校正';
                break;
            case 2:
                $pay_des = '准吖 - 运势';
                break;
            case 3:
                $pay_des = '准吖 - 占星地图';
                break;
            case 4:
                $pay_des = '准吖 - 占星视频';
                break;
            default :
                $pay_des = '';
        }

        /**
         * $account int 下单使用的商户配置id
         * 支付方式   1=>支付宝，2=>微信支付，5=>京东支付，6=>微信公众号支付，7=>支付宝手机网页支付，8=>微信H5网页支付
         */
        switch ($trade_type)
        {
            case 1:
                $account = intval(config('alipay.default'));
                break;
            case 2:
                $account = intval(config('wxpay.default'));
                break;
            case 5:
                $account = intval(config('jdpay.default'));
                break;
            case 6:
                $account = intval(config('wxpay.default'));
                break;
            case 7:
                $account = intval(config('alipay.default'));
                break;
            case 8:
                $account = intval(config('wxpay.default'));
                break;
            default:
                $account = 1;
                break;
        }

        /**
         * 更新支付方式 和 当前使用的支付配置
         */
        try
        {
            $OrdersModel->where(['order_id' => $order_id])->update(['trade_type' => $trade_type,'account' => $account]);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }

        // 删除订单缓存
        $OrdersModel->rm_cache(['uid' => $request->uid, 'type' => 2, 'order_id' => $order_id]);

        //支付订单
        $data = $OrdersLib->unifyPayOrder(['order_type' => $num, 'trade_type' => $trade_type, 'total_amount' => $order['total_amount'], 'pay_des' => $pay_des, 'order_id' => $order_id,'gid'=>$order['gid'], 'openid' => $openid, 'callback_url' => $callback_url, 'del_add' => 0]);

        return show(config('code.success'), '下单成功', $data['data']);

    }

    /**
     * 生时矫正下单接口
     * @return \response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \db\exception\DataNotFoundException
     * @throws \db\exception\ModelNotFoundException
     * @throws \exception\DbException
     */
    public function pay_order(Request $request)
    {
        if (!$request->isMethod('post'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $trade_type = $request->input('trade_type');// 支付方式
        $gid = $request->input('gid');// 商品类型id   1=>生时校正
        $id = $request->input('id') ?? 0;// 商品id =>生时校正id
        $openid = $request->input('openid', '');
        $callback_url = $request->input('callback_url', '');

        if (!$id)
        {
            return show(config('code.error'), '参数错误', [], 400);
        }

        //下单统一
        $OrderPayModel = new OrdersPayController();

        $data = $OrderPayModel->pay_unlock(['order_type' => 1, 'trade_type' => $trade_type, 'gid' => $gid, 'reid' => $id, 'openid' => $openid, 'callback_url' => $callback_url]);

        if ($data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);

        } else
        {
            return show(config('code.error'), '下单失败');
        }
    }

}
